package com.gz.logistics.app;

import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.gz.logistics.R;

public class DeviceListActivity extends BaseActivity {
	// 调试用
	private static final String TAG = DeviceListActivity.class.getSimpleName();
	private static final boolean D = true;

	// 返回时数据标签
	public static String EXTRA_DEVICE_ADDRESS = "设备地址";

	// 成员变量
	private BluetoothAdapter mBtAdapter;
	private ArrayAdapter<String> mPairedDevicesArrayAdapter;
	private ArrayAdapter<String> mNewDevicesArrayAdapter;
	private Dialog mLoadingData;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.device_list);
		setActionbarTitle("查找POS机设备", false);
		mLoadingData = new Dialog(this,R.style.DialogTheme);
		mLoadingData.setContentView(R.layout.loading_data_dialog2);
		mLoadingData.setCanceledOnTouchOutside(false);
		mLoadingData.setCancelable(false);
		// 得到本地蓝牙
		mBtAdapter = BluetoothAdapter.getDefaultAdapter();

		// 设置默认返回值为0 canceled
		setResult(Activity.RESULT_CANCELED);

		// 扫描按钮的响应事件，开始扫描和隐藏扫描按钮
		TextView scanButton = (TextView) findViewById(R.id.button_scan);
		scanButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				doDiscovery();
			}
		});
		//点击取消查找设备按钮返回到之前的页面
		TextView buttoncancel = (TextView) findViewById(R.id.button_cancel);
		buttoncancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		// 创建listview的适配器对象
		mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this,// 已配对
				R.layout.device_name);
		mNewDevicesArrayAdapter = new ArrayAdapter<String>(this,// 未配对
				R.layout.device_name);

		// 初始化已配对的listview
		ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
		pairedListView.setAdapter(mPairedDevicesArrayAdapter);
		pairedListView.setOnItemClickListener(mDeviceClickListener);

		// 初始化未配对的listview
		ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
		newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
		newDevicesListView.setOnItemClickListener(mDeviceClickListener);

		// 注册广播(查找到蓝牙设备)
		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		this.registerReceiver(mReceiver, filter);

		// 注册广播(查找结束)
		filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		this.registerReceiver(mReceiver, filter);
	}

	// 点击蓝牙条目的事件
	private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
								long id) {
			// 准备连接设备，关闭服务查找
			mBtAdapter.cancelDiscovery();

			// 得到mac地址
			String info = ((TextView) view).getText().toString();
			String address = info.substring(info.length() - 17);

			// 设置返回数据
			Intent intent = new Intent();
			intent.putExtra(EXTRA_DEVICE_ADDRESS, address);

			// 设置返回值并结束程序
			setResult(Activity.RESULT_OK, intent);
			finish();

		}
	};

	// 查找到设备和搜索完成action监听器，判断是否配对过，分别添加到两适配器中
	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			// 获取接收到的事件
			String action = intent.getAction();

			// 查找到设备
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				// 得到该蓝牙对象
				BluetoothDevice device = intent
						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				// 如果是已配对的则略过，已得到显示，其余的在添加到列表中进行显示
				if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
					mNewDevicesArrayAdapter.clear();
					mNewDevicesArrayAdapter.add(device.getName() + "\n"
							+ device.getAddress());
				} else { // 添加到已配对设备列表
					mPairedDevicesArrayAdapter.clear();
					mPairedDevicesArrayAdapter.add(device.getName() + "\n"
							+ device.getAddress());
				}
				// 搜索完成action
				mLoadingData.dismiss();
			} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
					.equals(action)) {
				setProgressBarIndeterminateVisibility(false);
				setTitle("选择要连接的设备");
				if (mNewDevicesArrayAdapter.getCount() == 0) {
					String noDevices = "没有找到新设备";
					mNewDevicesArrayAdapter.clear();
					mNewDevicesArrayAdapter.add(noDevices);
				}
			}
		}
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();

		// 关闭服务查找
		if (mBtAdapter != null) {
			mBtAdapter.cancelDiscovery();
		}

		// 注销action接收器
		this.unregisterReceiver(mReceiver);
	}

	public void OnCancel(View v) {
		finish();
	}

	// 查找附近蓝牙设备
	private void doDiscovery() {
		if (D)
			Log.d(TAG, "doDiscovery()");
		mLoadingData.show();
		setProgressBarIndeterminateVisibility(true); // 标题栏显示进度条
		setTitle("查找设备中...");// 在窗口显示查找中信息

		// 显示其它设备（未配对设备）列表
		findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);

		// 关闭再进行的服务查找
		if (mBtAdapter.isDiscovering()) {
			mBtAdapter.cancelDiscovery();
		}
		// 并重新开始
		mBtAdapter.startDiscovery();
	}
}
